import React, { useState } from 'react';
import { Button, Upload, message, Space, Modal } from 'antd';
import { DownloadOutlined, UploadOutlined, CloudDownloadOutlined } from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
import { post } from '@/utils/request';

export interface ExcelColumn {
  header: string;
  key: string;
  width?: number;
}

export interface ExportImportProps {
  // 导出配置
  onExport?: () => Promise<any[]> | any[];
  exportFilename?: string;
  exportColumns?: ExcelColumn[];
  exportSheetName?: string;
  exportButtonText?: string;
  showExportButton?: boolean;
  
  // 导入配置
  onImport?: (data: any[]) => Promise<void> | void;
  importButtonText?: string;
  showImportButton?: boolean;
  
  // 模板配置
  templateFilename?: string;
  templateColumns?: ExcelColumn[];
  templateSampleData?: any[];
  showTemplateButton?: boolean;
  templateButtonText?: string;
  
  // 验证函数
  validateImportData?: (data: any[]) => { valid: boolean; errors?: string[] };
  
  // 样式
  buttonSize?: 'small' | 'middle' | 'large';
  buttonType?: 'default' | 'primary' | 'dashed' | 'link' | 'text';
}

/**
 * 导出导入通用组件
 * 前端只需提供数据和配置，后端处理Excel生成
 */
export const ExportImport: React.FC<ExportImportProps> = ({
  onExport,
  exportFilename = 'export',
  exportColumns = [],
  exportSheetName = 'Sheet1',
  exportButtonText = '导出',
  showExportButton = true,
  
  onImport,
  importButtonText = '导入',
  showImportButton = true,
  
  templateFilename,
  templateColumns,
  templateSampleData,
  showTemplateButton = false,
  templateButtonText = '下载模板',
  
  validateImportData,
  
  buttonSize = 'middle',
  buttonType = 'default',
}) => {
  const [exportLoading, setExportLoading] = useState(false);
  const [importLoading, setImportLoading] = useState(false);

  /**
   * 导出数据
   */
  const handleExport = async () => {
    if (!onExport) {
      message.warning('未配置导出功能');
      return;
    }

    setExportLoading(true);
    try {
      const data = await onExport();
      
      if (!data || data.length === 0) {
        message.warning('没有数据可导出');
        setExportLoading(false);
        return;
      }

      // 调用后端导出接口
      const response = await post('/export-import/export', {
        filename: exportFilename,
        sheetName: exportSheetName,
        columns: exportColumns,
        data,
      }, {
        responseType: 'blob',
      } as any);

      // 创建下载链接
      const blob = new Blob([response as any], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `${exportFilename}_${Date.now()}.xlsx`;
      link.click();
      window.URL.revokeObjectURL(url);

      message.success('导出成功');
    } catch (error: any) {
      console.error('导出失败:', error);
      message.error(error.message || '导出失败');
    } finally {
      setExportLoading(false);
    }
  };

  /**
   * 下载导入模板
   */
  const handleDownloadTemplate = async () => {
    if (!templateColumns || templateColumns.length === 0) {
      message.warning('未配置模板');
      return;
    }

    try {
      const params = new URLSearchParams({
        filename: templateFilename || exportFilename,
        columns: JSON.stringify(templateColumns),
      });

      if (templateSampleData) {
        params.append('sampleData', JSON.stringify(templateSampleData));
      }

      const token = localStorage.getItem('access_token');
      const url = `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:4321/api'}/export-import/template?${params.toString()}&token=${token}`;
      
      // 下载
      const link = document.createElement('a');
      link.href = url;
      link.download = `${templateFilename || exportFilename}_template.xlsx`;
      link.click();

      message.success('模板下载成功');
    } catch (error: any) {
      console.error('下载模板失败:', error);
      message.error(error.message || '下载模板失败');
    }
  };

  /**
   * 处理文件导入
   */
  const handleImport = async (file: UploadFile) => {
    if (!onImport) {
      message.warning('未配置导入功能');
      return;
    }

    setImportLoading(true);
    try {
      const formData = new FormData();
      formData.append('file', file as any);

      // 调用后端解析接口
      const response = await post<{ total: number; data: any[] }>('/export-import/import', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      } as any);

      if (!response.data.success || !response.data.data) {
        message.error('解析失败');
        setImportLoading(false);
        return;
      }

      const { data } = response.data.data;

      if (!data || data.length === 0) {
        message.warning('文件中没有数据');
        setImportLoading(false);
        return;
      }

      // 验证数据
      if (validateImportData) {
        const validation = validateImportData(data);
        if (!validation.valid) {
          Modal.error({
            title: '数据验证失败',
            content: (
              <div>
                {validation.errors?.map((error, index) => (
                  <div key={index} style={{ marginBottom: 8 }}>
                    • {error}
                  </div>
                ))}
              </div>
            ),
          });
          setImportLoading(false);
          return;
        }
      }

      // 执行导入
      await onImport(data);
      message.success(`成功导入 ${data.length} 条数据`);
    } catch (error: any) {
      console.error('导入失败:', error);
      message.error(error.message || '导入失败');
    } finally {
      setImportLoading(false);
    }

    return false; // 阻止默认上传行为
  };

  return (
    <Space size="small">
      {/* 下载模板按钮 */}
      {showTemplateButton && templateColumns && (
        <Button
          size={buttonSize}
          type={buttonType}
          icon={<CloudDownloadOutlined />}
          onClick={handleDownloadTemplate}
        >
          {templateButtonText}
        </Button>
      )}

      {/* 导出按钮 */}
      {showExportButton && onExport && exportColumns.length > 0 && (
        <Button
          size={buttonSize}
          type={buttonType}
          icon={<DownloadOutlined />}
          onClick={handleExport}
          loading={exportLoading}
        >
          {exportButtonText}
        </Button>
      )}

      {/* 导入按钮 */}
      {showImportButton && onImport && (
        <Upload
          accept=".xlsx,.xls"
          showUploadList={false}
          beforeUpload={handleImport}
        >
          <Button
            size={buttonSize}
            type={buttonType}
            icon={<UploadOutlined />}
            loading={importLoading}
          >
            {importButtonText}
          </Button>
        </Upload>
      )}
    </Space>
  );
};

export default ExportImport;
